package com.xiaoyun.zklock.controller;

import com.xiaoyun.zklock.zklock.ZkLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class ZookeeperController {

    @Autowired
    private CuratorFramework curatorFramework;
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/")
    public String zookeeperLock() {
        log.info("进入了方法");
        try (ZkLock zkLock = new ZkLock()) {
            if (zkLock.getLock("order")) {
                log.info("获取了zkLock");
                Thread.sleep(10000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("方法执行完成zkLock");
        return "ok";
    }

    @GetMapping("/cu")
    public String curatorLock() {
        log.info("进入了方法");
        String lockPath = "/order";
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, lockPath);
        try {
            if (lock.acquire(30, TimeUnit.SECONDS)) {
                try {
                    log.info("我获得了锁!!");
                    Thread.sleep(10000);
                } finally {
                    lock.release();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("方法执行完成zkLock");
        return "ok";
    }

    @GetMapping("/re")
    public String redissonLock() {
        log.info("进入了方法");
        String lock = "order";

        RLock rLock = redissonClient.getLock(lock);
        rLock.lock(30, TimeUnit.SECONDS);
        log.info("我获得了锁!!");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        log.info("方法执行完成zkLock");
        return "ok";
    }
}
